package online.dgyj.nle_cloudsdk;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;
import java.util.List;

import cn.com.newland.nle_sdk.requestEntity.SignIn;
import cn.com.newland.nle_sdk.responseEntity.SensorInfo;
import cn.com.newland.nle_sdk.responseEntity.User;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.CloudService;
import cn.com.newland.nle_sdk.util.CloudServiceListener;

@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Handler handler;
    private static final String baseURL = "https://api.nlecloud.com/";
    private CloudService cloudService;
    private String user;
    private String pwd;
    private int projectID;
    private List<SensorInfo> sensorInfoList;
    private ArrayList<String> sensorList = new ArrayList<>();

    private EditText SensorDataText, ProjectEdit, UserEdit, PwdEdit;
    private Button LoginBtn, GetBtn, SendBtn;
    private Spinner sensorSpinner1, sensorSpinner2;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        bind();
    }

    /**
     * 实例化视图
     */
    private void bind() {
        handler = new Handler(Looper.getMainLooper());

        LoginBtn = findViewById(R.id.LoginBtn);
        GetBtn = findViewById(R.id.SendBtn);
        SendBtn = findViewById(R.id.getBtn);
        sensorSpinner1 = findViewById(R.id.sensorSpinner1);
        sensorSpinner2 = findViewById(R.id.sensorSpinner2);

        ProjectEdit = findViewById(R.id.ProjectEdit);
        UserEdit = findViewById(R.id.UserEdit);
        PwdEdit = findViewById(R.id.PwdEdit);
        SensorDataText = findViewById(R.id.SensorDataText);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, sensorList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sensorSpinner1.setAdapter(adapter);
        sensorSpinner2.setAdapter(adapter);

        LoginBtn.setOnClickListener(this);
        GetBtn.setOnClickListener(this);
        SendBtn.setOnClickListener(this);
    }

    /**
     * 获取项目中全部的传感器并更新到View上
     */
    private void GetAllSensor() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                cloudService.getAllSensors(projectID, new CloudServiceListener<BaseResponseEntity<List<SensorInfo>>>() {
                    @Override
                    protected void onResponse(BaseResponseEntity<List<SensorInfo>> listBaseResponseEntity) {
                        sensorInfoList = listBaseResponseEntity.getResultObj();
                        for (int i = 0; i < sensorInfoList.size(); i++) {
                            sensorList.add(sensorInfoList.get(i).getApiTag());
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                });
            }
        }).start();
    }

    /**
     * 获取传感器数据
     *
     * @return Thread
     */
    private Thread GetSensorData() {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                int deviceID = sensorInfoList.get(sensorSpinner1.getSelectedItemPosition()).getDeviceID();
                String apiTag = sensorSpinner1.getSelectedItem().toString();
                cloudService.getSensors(deviceID, apiTag, new CloudServiceListener<BaseResponseEntity<List<SensorInfo>>>() {
                    @Override
                    protected void onResponse(BaseResponseEntity<List<SensorInfo>> listBaseResponseEntity) {
                        String val = listBaseResponseEntity.getResultObj().get(0).getValue();
                        Log.d(apiTag, val);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), String.format("%s:%s", apiTag, val), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 发送指令
     *
     * @return 线程
     */
    private Thread SendData() {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                int deviceID = sensorInfoList.get(sensorSpinner2.getSelectedItemPosition()).getDeviceID();
                String apiTag = sensorSpinner2.getSelectedItem().toString();
                // 如果传感器的数据类型为字符型,则发送String
                if (sensorInfoList.get(sensorSpinner2.getSelectedItemPosition()).getDataType() == 3) {
                    cloudService.control(deviceID, apiTag, SensorDataText.getText().toString(), new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {

                        }
                    });
                }
                // 若为其它类型,这发送int
                else {
                    cloudService.control(deviceID, apiTag, Integer.parseInt(SensorDataText.getText().toString()), new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {

                        }
                    });
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        // 登录
        if (v.getId() == R.id.LoginBtn) {
            if (cloudService == null) {

                projectID = Integer.parseInt(ProjectEdit.getText().toString());
                user = UserEdit.getText().toString();
                pwd = PwdEdit.getText().toString();
                cloudService = new CloudService(baseURL);

                cloudService.signIn(new SignIn(user, pwd), new CloudServiceListener<BaseResponseEntity<User>>() {
                    @Override
                    protected void onResponse(BaseResponseEntity<User> userBaseResponseEntity) {
                        Log.d("AccessToken", userBaseResponseEntity.getResultObj().getAccessToken());
                        cloudService.setAccessToken(userBaseResponseEntity.getResultObj().getAccessToken());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ProjectEdit.setEnabled(false);
                                UserEdit.setEnabled(false);
                                PwdEdit.setEnabled(false);
                                LoginBtn.setText("Quit");
                            }
                        });
                        GetAllSensor();
                    }
                });
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ProjectEdit.setEnabled(true);
                        UserEdit.setEnabled(true);
                        PwdEdit.setEnabled(true);
                        adapter.clear();
                        adapter.notifyDataSetChanged();
                        LoginBtn.setText("Login");
                    }
                });
                cloudService = null;
            }
        }
        // 获取
        else if (v.getId() == R.id.getBtn) {
            if (cloudService != null)
                GetSensorData().start();
        }
        // 发送
        else if (v.getId() == R.id.SendBtn) {
            if (cloudService != null)
                SendData().start();
        }
    }
}